package com.lsj.config.security.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lsj.core.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author:lin.sj
 * @Data:2021/7/6 22:41
 * @Desc: jwt登录过滤器
 */
@Service
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //从请求中提取token
        String jwtToken = request.getHeader(jwtTokenUtil.getHeader());
        //判断token ！= null 且尚无认证信息在security中
        if(StringUtils.isNotBlank(jwtToken) && SecurityContextHolder.getContext().getAuthentication() == null) {
            if (!jwtTokenUtil.isTokenExpired(jwtToken)) {
                //提取用户名,如果token已过期，username将提取不出来
                String username = jwtTokenUtil.getUsernameFromToken(jwtToken);
                if (StringUtils.isNotBlank(username)) {
                    //加载用户信息
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    //验证token是否有效
                    if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
                        //构建认证的authentication，设置到SecurityContextHolder中，供本次调用的后续使用
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                }
            }
        }
        filterChain.doFilter(request,response);
    }
}
